<template>
	<view class="">
		<!-- 消防控制室值班记录表 -->
		<view class="files">
			<view class="tabs">
				<fui-list bottomBorder title="巡查人员基本信息">
					<view class="tab">
						<fui-list-cell>
							<text>巡查人员</text>
							<text class="fui-text__explain">{{ inspectionStaff.name }}</text>
						</fui-list-cell>

						<fui-list-cell>
							<text>巡查日期</text>
							<text class="fui-text__explain">{{ inspectionStaff.data }}</text>
						</fui-list-cell>

						<fui-input @longpress="showColumns=!showColumns" required v-model="controllerModel"
							label="控制器型号" textAlign="right" placeholder="请输入"></fui-input>
					</view>
				</fui-list>

				<fui-list bottomBorder title="控制器日检测情况">
					<view class="tab">
						<fui-input required v-model="time" label="时间（时/分）" readonly textAlign="right"
							placeholder="请输入"></fui-input>

						<fui-input required readonly @click="onShowOps(1)" v-model="dailyInspection.selfExamination"
							label="自检" textAlign="right" placeholder="请选择"></fui-input>

						<fui-input required readonly @click="onShowOps(2)" v-model="dailyInspection.muffling" label="消音"
							textAlign="right" placeholder="请选择"></fui-input>
						<fui-input required readonly @click="onShowOps(6)" v-model="dailyInspection.reset" label="复位"
							textAlign="right" placeholder="请选择"></fui-input>

						<fui-input required readonly @click="onShowOps(3)" v-model="dailyInspection.mainPowerSupply"
							label="主电源" textAlign="right" placeholder="请选择"></fui-input>

						<fui-input required readonly @click="onShowOps(4)"
							v-model="dailyInspection.emergencyPowerSupply" label="备用电源" textAlign="right"
							placeholder="请选择"></fui-input>

						<fui-input required v-model="inspectionStaff.name" label="检测人" textAlign="right"
							placeholder="请输入"></fui-input>
						<fui-input label="故障" readonly></fui-input>
						<u--textarea v-model="dailyInspection.malfunction" placeholder="请输入内容" count
							maxlength="250"></u--textarea>

						<fui-input label="处理情况" readonly></fui-input>
						<u--textarea v-model="dailyInspection.handlingSituation" placeholder="请输入内容" count
							maxlength="250"></u--textarea>
					</view>
				</fui-list>

				<fui-list bottomBorder title="控制器日运行情况记录">
					<view class="tab">
						<fui-input required v-model="time" label="时间（时/分）" readonly textAlign="right"
							placeholder="请选择"></fui-input>

						<fui-input placeholder="请选择" @click="onShowOps(5)" readonly required
							v-model="operationCondition.operationCondition" label="控制器运行情况"
							textAlign="right"></fui-input>

						<fui-input placeholder="请选择" readonly @click="showOpsTow = !showOpsTow" required
							v-model="operationCondition.alarmNature" label="报警性质" textAlign="right"></fui-input>

						<fui-input required v-model="operationCondition.alarmPosition" label="报警部位" textAlign="right"
							placeholder="请输入"></fui-input>

						<fui-input label="原因" readonly></fui-input>
						<u--textarea v-model="operationCondition.alarmReason" placeholder="请输入内容" count
							maxlength="250"></u--textarea>

						<fui-input label="处理情况" readonly></fui-input>
						<u--textarea v-model="operationCondition.alarmProcessing" placeholder="请输入内容" count
							maxlength="250"></u--textarea>
					</view>
				</fui-list>

				<!-- 	<fui-list bottomBorder title="控制器日报警记录" v-if="dyMsg.length > 0">
					<view  class="tab"  >
						<view style="padding-bottom: 40rpx;" v-for="(item, index) in dyMsg">
							<fui-input :label="'报警记录' + (index + 1)" readonly   textAlign="right"></fui-input>
							<fui-input label="报警日期" v-model="item.time"  readonly   textAlign="right"></fui-input>
							<fui-input label="报警性质" v-model="item.nature"  readonly   textAlign="right"></fui-input>
							<fui-input label="报警部位" v-model="item.position"  readonly   textAlign="right"></fui-input>
							<fui-input label="原因" v-model="item.reason"  readonly   textAlign="right"></fui-input>
							<br />
							<fui-button @click="onIntegration(item)"  background="#409EFF" width="95%" style="margin: 0 auto;" type="success">一键整合</fui-button>
						</view>
					</view>
					
					
				</fui-list> -->
			</view>

			<view class="tab_ops">
				<!-- 	<view style="width: 100%; display: flex; justify-content: space-between;">
					<fui-button btnSize="small" >巡查人员签字</fui-button>
					<fui-button btnSize="small"  >安全主管签字</fui-button>
				</view> -->
				<view style="padding-top: 40rpx">
					<fui-button @click="submit" type="success">提交</fui-button>
				</view>
			</view>
			<view>
				<u-picker @confirm="onOpsOne" @cancel="showOpsOne = !showOpsOne" :show="showOpsOne"
					:columns="columnsOne"></u-picker>
			</view>
			<view>
				<u-picker @confirm="onOpsTow" @cancel="showOpsTow = !showOpsTow" :show="showOpsTow"
					:columns="columnsTow"></u-picker>
			</view>
		</view>
		<view>
			<up-picker @confirm="onColumns" @cancel="showColumns = !showColumns" :show="showColumns"
				:columns="columns"></up-picker>
		</view>
	</view>
</template>

<script>
	import moment, {
		duration
	} from 'moment';
	import {
		BASE_IP
	} from '@/common/http/url.js';
	// import test from '../../../uni_modules/uview-plus/libs/function/test';
	// import text from '../../../uni_modules/uview-plus/libs/config/props/text';
	import tools from '@/tools/tools.js';

	export default {
		name: 'fireControlRoom',
		data() {
			return {
				user: '',
				inspectionStaff: {
					name: '',
					data: '',
					time: ''
				},
				situation: '',
				columnsOne: [
					['正常', '异常']
				],
				columnsTow: [
					['火警', '误报', '故障报警', '漏报', '无']
				],
				showOpsOne: false,
				showOpsTow: false,
				regime: '',
				year: '',
				month: '',
				day: '',
				dailyInspection: {
					selfExamination: '正常', //自检
					muffling: '正常', //消音
					reset: '正常', //复位
					mainPowerSupply: '正常', //主电源
					emergencyPowerSupply: '正常', //备用电源
					malfunction: '', //故障
					handlingSituation: '' //处理情况
				},
				operationCondition: {
					operationCondition: '正常', //控制器运行情况
					alarmNature: '无', //报警性质
					alarmPosition: '无', //报警部位
					alarmReason: '无', //报警原因
					alarmProcessing: '无' //报警处理情况
				},
				controllerModel: '',
				time: '',
				index: 0,
				isSubmit: false,
				msgs: [],
				dyMsg: [],
				columns: [
					[]
				],
				showColumns: false,
				preset: ""
			};
		},
		methods: {
			onColumns(res) {
				console.log(res)
				this.controllerModel = res.value[0]
				this.showColumns = !this.showColumns
			},
			onIntegration(res) {
				this.operationCondition.operationCondition = "异常"
				this.operationCondition.alarmNature = res.nature
				this.operationCondition.alarmPosition = res.position
				this.operationCondition.alarmReason = res.reason
				uni.showModal({
					title: "提示",
					content: "整合完毕",
					showCancel: false,
					success() {

					}
				})
				console.log(res)
			},
			/**
			 *
			 * @param {Object} path 转入要签字的路径
			 */
			onSignatures(path) {
				let user = uni.getStorageSync('user');
				if (user.signature == '' || user.signature == undefined || user.signature == null) {
					uni.showModal({
						title: '提示',
						content: '用户未上传签名请前往“预设功能-添加操作员-输入账号-添加签名”，如果已添加操作员上传签名即可',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return;
							}
						}
					});
					return;
				}
				let docPath = path;
				let url = BASE_IP + user.signature;
				tools.upSignatures(path, user.signature);
				// console.log(url)
				// let _this = this
				// uni.downloadFile({ //下载
				// 	url: url, //图片下载地址
				// 	success: res => {
				// 		if (res.statusCode === 200) {
				// 			uni.saveFile({
				// 				tempFilePath: res.tempFilePath,
				// 				success: (r) => {
				// 					console.log(r)
				// 					_this.upSignatures(r.savedFilePath, docPath)
				// 				}
				// 			})
				// 		}
				// 	}
				// });
			},
			/** 签字函数
			 * @param {Object} filePath 签字图片
			 * @param {Object} docPath  要签字的文档
			 */
			upSignatures(filePath, docPath) {
				console.log(filePath, docPath);
				let user = uni.getStorageSync('user');
				let url = BASE_IP + 'pc/regulatory/signature/word';
				uni.uploadFile({
					header: {
						Authorization: user.token
					},
					name: 'file',
					url: url,
					formData: {
						unitId: user.unitId,
						path: docPath
					},
					filePath: filePath,
					success: (res) => {
						if (res.statusCode == 500) {
							uni.showToast({
								title: '上传失败',
								icon: 'error'
							});
							return;
						}
					},
					fail: (res) => {
						uni.showToast({
							title: '上传失败,请重试',
							icon: 'error'
						});
					}
				});
			},
			/**
			 * 盖章
			 * @param {Object} path 转入要盖章的文件路径
			 */
			onSeal(path) {
				let pralldata = uni.getStorageSync('pralldata');
				// console.log(pralldata)
				let docPath = path;
				if (pralldata.unitFireSeal == '' || pralldata.unitFireSeal == undefined) {
					uni.showModal({
						title: '提示',
						content: '单位未上传消防专用章',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return;
							}
						}
					});
					return;
				}
				let url = BASE_IP + pralldata.unitFireSeal;
				tools.upLoadSeal(path, pralldata.unitFireSeal);
				// console.log(url)
				// uni.downloadFile({ //下载
				// 	url: url, //图片下载地址
				// 	success: res => {
				// 		if (res.statusCode === 200) {
				// 			uni.saveFile({
				// 				tempFilePath: res.tempFilePath,
				// 				success: (r) => {
				// 					// console.log(r)
				// 					this.upLoadSeal(r.savedFilePath, docPath)
				// 				}
				// 			})
				// 		}
				// 	}
				// });
			},
			/** 盖章函数
			 * @param {Object} filePath 印章图片
			 * @param {Object} docPath  要盖章的文档
			 */
			upLoadSeal(filePath, docPath) {
				let user = uni.getStorageSync('user');
				let url = BASE_IP + 'pc/regulatory/update/word';
				uni.uploadFile({
					header: {
						Authorization: user.token
					},
					name: 'file',
					url: url,
					formData: {
						unitId: user.unitId,
						path: docPath
					},
					filePath: filePath,
					success: (res) => {
						// console.log(res)
						if (res.statusCode == 500) {
							uni.showToast({
								title: '盖章失败',
								icon: 'error'
							});
							return;
						}
						if (res.statusCode == 404) {
							uni.showToast({
								title: '盖章失败',
								icon: 'error'
							});
							return;
						}
					},
					fail: (res) => {
						uni.showToast({
							title: '盖章失败,请重试',
							icon: 'error'
						});
					}
				});
			},
			onShowOps(index) {
				this.index = index;
				this.showOpsOne = !this.showOpsOne;
			},
			onOpsTow(res) {
				this.operationCondition.alarmNature = res.value[0];
				this.showOpsTow = !this.showOpsTow;
			},
			onOpsOne(res) {
				// this.situation = res.value[0]
				// console.log(res)
				switch (this.index) {
					case 1: {
						this.dailyInspection.selfExamination = res.value[0];
						break;
					}
					case 2: {
						this.dailyInspection.muffling = res.value[0];
						break;
					}
					case 3: {
						this.dailyInspection.mainPowerSupply = res.value[0];
						break;
					}
					case 4: {
						this.dailyInspection.emergencyPowerSupply = res.value[0];
						break;
					}
					case 5: {
						this.operationCondition.operationCondition = res.value[0];
						break;
					}
					case 6: {
						this.dailyInspection.reset = res.value[0];
						break;
					}
				}
				this.showOpsOne = !this.showOpsOne;
			},
			submit() {
				if (this.isSubmit) {
					uni.showToast({
						title: '请勿重复提交',
						icon: 'error'
					});
					return;
				}


				let url = BASE_IP + 'pc/record/record/fire/dutyRecordFormFireControlRoom';

				let classifyId = this.regime.classifyId;
				// console.log(this.regime)
				let user = uni.getStorageSync('user');
				if (this.dailyInspection.alarmProcessing == '') {
					this.dailyInspection.alarmProcessing = '无';
				}
				if (this.dailyInspection.alarmReason == '') {
					this.dailyInspection.alarmReason = '无';
				}
				if (this.operationCondition.alarmPosition == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}
				if (this.operationCondition.alarmNature == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}
				if (this.operationCondition.operationCondition == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}
				if (this.dailyInspection.handlingSituation == '') {
					this.dailyInspection.handlingSituation = '无';
				}
				if (this.dailyInspection.malfunction == '') {
					this.dailyInspection.malfunction = '无';
				}

				if (this.dailyInspection.muffling == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}
				if (this.dailyInspection.reset == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}
				if (this.dailyInspection.mainPowerSupply == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}
				if (this.dailyInspection.emergencyPowerSupply == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}

				if (this.dailyInspection.selfExamination == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}

				if (this.controllerModel == '') {
					uni.showToast({
						icon: 'error',
						title: '表单填写不完整'
					});
					return;
				}

				if (this.inspectionStaff.name == '') {
					uni.showToast({
						icon: 'error',
						title: '检测人未填'
					});
					return;
				}


				let json1 = {
					name: this.inspectionStaff.name,
					data: this.inspectionStaff.data,
					time: this.time,
					v1: this.controllerModel,
					v2: this.dailyInspection.selfExamination,
					v3: this.dailyInspection.muffling,
					v4: this.dailyInspection.reset,
					v5: this.dailyInspection.mainPowerSupply,
					v6: this.dailyInspection.emergencyPowerSupply,
					v7: this.dailyInspection.malfunction,
					v8: this.dailyInspection.handlingSituation,
					c1: this.operationCondition.operationCondition,
					c2: this.operationCondition.alarmNature,
					c3: this.operationCondition.alarmPosition,
					c4: this.operationCondition.alarmReason,
					c5: this.operationCondition.alarmProcessing
				};
				if (json1.c4 == "") {
					json1.c4 = "无"
				}
				if (json1.c5 == "") {
					json1.c5 = "无"
				}

				if (json1.c1 == "异常") {
					if (json1.c2 == "无" || json1.c2 == "") {
						uni.showModal({
							title: "提示",
							content: "控制器日运行情况记录情况异常\n请填写报警性质"
						})
						return
					}
					if (json1.c3 == "无" || json1.c3 == "") {
						uni.showModal({
							title: "提示",
							content: "控制器日运行情况记录情况异常\n请填写报警部位"
						})
						return
					}
					if (json1.c4 == "无" || json1.c4 == "") {
						uni.showModal({
							title: "提示",
							content: "控制器日运行情况记录情况异常\n请填写原因"
						})
						return
					}
					if (json1.c5 == "无" || json1.c5 == "") {
						uni.showModal({
							title: "提示",
							content: "控制器日运行情况记录情况异常\n请填写处理情况"
						})
						return
					}
					uni.hideLoading();
				}

				if (json1.v2 == "异常") {
					if (json1.v7 == "无" || json1.v7 == "") {
						uni.showModal({
							title: "提示",
							content: "自检情况异常\n请填写故障处理"
						})
						return
					}
					if (json1.v8 == "无" || json1.v8 == "") {
						uni.showModal({
							title: "提示",
							content: "自检情况异常\n请填写处理情况"
						})
						return
					}
				}

				if (json1.v3 == "异常") {
					if (json1.v7 == "无" || json1.v7 == "") {
						uni.showModal({
							title: "提示",
							content: "消音情况异常\n请填写故障处理"
						})
						return
					}
					if (json1.v8 == "无" || json1.v8 == "") {
						uni.showModal({
							title: "提示",
							content: "消音情况异常\n请填写处理情况"
						})
						return
					}
				}

				if (json1.v4 == "异常") {
					if (json1.v7 == "无" || json1.v7 == "") {
						uni.showModal({
							title: "提示",
							content: "复位情况异常\n请填写故障处理"
						})
						return
					}
					if (json1.v8 == "无" || json1.v8 == "") {
						uni.showModal({
							title: "提示",
							content: "复位情况异常\n请填写处理情况"
						})
						return
					}
				}

				if (json1.v5 == "异常") {
					if (json1.v7 == "无" || json1.v7 == "") {
						uni.showModal({
							title: "提示",
							content: "主电源情况异常\n请填写故障处理"
						})
						return
					}
					if (json1.v8 == "无" || json1.v8 == "") {
						uni.showModal({
							title: "提示",
							content: "主电源情况异常\n请填写处理情况"
						})
						return
					}
				}

				if (json1.v6 == "异常") {
					if (json1.v7 == "无" || json1.v7 == "") {
						uni.showModal({
							title: "提示",
							content: "备用电源情况异常\n请填写故障处理"
						})
						return
					}
					if (json1.v8 == "无" || json1.v8 == "") {
						uni.showModal({
							title: "提示",
							content: "备用电源情况异常\n请填写处理情况"
						})
						return
					}
				}

				console.log(json1)
				let flag_storage = true
				// let user = uni.getStorageSync("user")
				if (user.signature == "" || user.signature == undefined || user.signature == null) {
					uni.showModal({
						title: "提示",
						content: "用户未上传签名请前往“预设功能-添加操作员-输入账号-添加签名”，如果已添加操作员上传签名即可",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								
								flag_storage = false
								uni.navigateTo({
									url: "/pages/preinstall/preinstall"
								})
								return
							}
						}
					})
					return
				}
				
				if (!flag_storage) {
					return
				}
				
				let pralldata = this.preset
				console.log(pralldata)
				let falg_seal = true
				if (pralldata.unitFireSeal == "" || pralldata.unitFireSeal == undefined) {
					uni.showModal({
						title: "提示",
						content: "单位未上传消防专用章,请前往“预设功能-单位消防专用章”上传",
						showCancel: false,
						success: (res) => {
								
							if (res.confirm) {
								
								falg_seal = false
								uni.navigateTo({
									url: "/pages/preinstall/preinstall"
								})
								return
							}
						}
					})
					return
				}
				
				if (!falg_seal) {
					return
				}

				uni.showLoading({
					title: '正在提交'
				});

				this.isSubmit = !this.isSubmit;
				// console.log(json1)

				uni.request({
					url: url,
					header: {
						Authorization: user.token,
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						unitId: user.unitId,
						name: user.nickName,
						classifyId: classifyId,
						json: JSON.stringify(json1),
						uuid : user.uuid
					},
					method: 'POST',
					success: (res) => {
						console.log(res);

						if (res.statusCode == 200) {
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							});

							// this.onSeal(res.data.path);
							// this.onSignatures(res.data.path);
							setTimeout((r) => {
								uni.navigateBack({
									delta: 1,
									success: function() {
										const pages = getCurrentPages(); //获取当前页面栈
										const prevPage = pages[pages.length -
											1]; //获取上一个页面实例对象
										prevPage.getCollapseDatas(); //调用上一个页面的onLoad方法
									}
								});
							}, 1500);
							return;
						}

						if (res.statusCode == 500) {
							uni.showToast({
								title: '上传失败',
								icon: 'error'
							});
							this.isSubmit = !this.isSubmit
							return;
						}
						if (res.statusCode == 404) {
							uni.showToast({
								title: '上传失败',
								icon: 'error'
							});
							this.isSubmit = !this.isSubmit
							return;
						}
					},
					fail: (res) => {
						uni.showToast({
							title: '上传失败',
							icon: 'error'
						});
						this.isSubmit = !this.isSubmit
					}
				});
			},
			getPrall() { //获取预设功能对象数据
			let pralldata = uni.getStorageSync("pralldata")
			this.preset = pralldata
				// let user = uni.getStorageSync("user")
				// let url = BASE_IP + "pc/presetfunction/find/presetFunction/" + user.unitId + "/" + user.uuid
				// uni.request({
				// 	header: {
				// 		"Authorization": user.token,
				// 	},
				// 	url: url,
				// 	success: (res) => {
				// 		this.preset = res.data
				// 	},
				// 	fail: (res) => {
				// 		// console.log("请求失败：", res)
				// 	}
				// })
			}
		},
		onLoad(ops) {
			uni.setNavigationBarTitle({
				title: '消防控制室值班记录表'
			});
			this.getPrall()
			const currentDate = moment();
			const year = currentDate.year();
			const month = currentDate.month() + 1;
			const day = currentDate.date();

			let date = year + "-" + month + "-" + day

			let msgs = uni.getStorageSync('msgs');

			for (let m in msgs) {
				if (msgs[m].type == 2) {
					this.msgs.push(msgs[m]);
				}
			}

			// console.log("消息==>",this.msgs)

			// 假设 msgs 是你的消息数组

			if (this.msgs.length > 0) {
				let today = moment(); // 获取当前日期
				let todayStr = today.format('YYYY-MM-DD'); // 将日期格式化为字符串并只取日期部分

				// 遍历消息数组
				for (let msg of this.msgs) {
					let msgDate = moment(msg.time); // 将消息的时间字符串转换为 Moment.js 对象
					let msgDateStr = msgDate.format('YYYY-MM-DD'); // 将消息的日期格式化为字符串并只取日期部分

					console.log("msgDate===>", msgDate.format()); // 输出消息的日期和时间
					console.log("todayStr===>", today.format()); // 输出今天的日期和时间

					if (msgDateStr === todayStr) {
						// 如果是今天的消息，进行相应操作
						// console.log("今天的消息:", msg);
						this.dyMsg.push(msg);
					} else {
						console.log('不是今天的消息:', msg);
					}
				}
			}



			let user = uni.getStorageSync('user');
			// console.log(user)
			this.regime = JSON.parse(ops.regime);
			// console.log(this.regime)
			this.inspectionStaff.name = user.nickName;



			this.year = year;
			this.month = month + '月';
			this.day = day;
			this.inspectionStaff.data = year + '-' + month + '-' + day;

			let pralldata = uni.getStorageSync('pralldata');

			this.inspectionStaff.time = pralldata.operatingTimeStart + ' - ' + pralldata.operatingTimeEnd;

			const currentTime = moment().format('HH:mm');
			this.time = currentTime;
			// console.log("获取当前时间：", currentTime);
			let recordTable = uni.getStorageSync('recordTable');
			recordTable.t4 = JSON.parse(recordTable.t4)
			for (let index in recordTable.t4) {
				this.columns[0].push(recordTable.t4[index])
			}
			this.controllerModel = recordTable.t4[0];

			if (this.dyMsg.length > 0) {
				uni.showModal({
					title: '提示',
					content: '请注意报警器出现一次或多次报警',
					showCancel: false,
					success: (res) => {

					}
				});
			}
			setTimeout(() => {
				uni.showModal({
					title: '提示',
					content: '是否全部正常',
					cancelText: '否',
					confirmText: '是',
					success: (res) => {
						if (res.cancel) {}
						if (res.confirm) {

							this.submit();
						}
					}
				});
			}, 800);
		}
	};
</script>

<style>
	page {
		background-color: #f1f4fa;
	}

	.tabs {
		width: 95%;
		margin: auto;
	}

	.tab {
		width: 100%;
		background-color: white;
		border-radius: 8px;
		/* margin: auto; */
		box-shadow: 1px 1px 10px #dcdfe6;
		padding-top: 10rpx;
		padding-bottom: 20rpx;
	}

	.fui-text__explain {
		font-size: 14px;
		color: #606266;
	}

	.tab_ops {
		padding: 40rpx;
		padding: 40rpx;
	}
</style>